<?php

namespace App\Http\Controllers\Api\v1;

use App\Carousel as CarouselModel;
use App\Http\Controllers\Api\BaseController;
use App\Http\Requests\CarouselRequest;
use App\Http\Resources\Carousel;
use App\Http\Resources\CarouselCollection;
use App\Repositories\CarouselRepository;
use App\Traits\BaseApiFunc;
use Auth;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CarouselController extends BaseController {

	use BaseApiFunc;

	protected $model, $page_size;

	public function __construct(CarouselRepository $carousel) {
		parent::__construct();

		$this->model = $carousel;
		$this->page_size = config('blog.admin_page.carousel_page');
	}

	public function index(Request $request) {
		$page = (int) $request->query('page', 1);
		$page_size = $this->page_size;
		$total_nums = $this->model->countRaws();

		$list = $this->getResourceCollection($this->model->page($page, $page_size))->additional(['meta' => compact(
			'total_nums', 'page_size', 'page')]);

		return $this->response->withCollectionSuccess($list);
	}

	public function store(CarouselRequest $request) {
		$carousel = $this->model->store(array_merge(['user_id' => Auth::user()->id], $request->all()));
		return $this->response->withSuccess($carousel);
	}

	public function carousels() {
		$list = Cache::remember('carousels', config('blog.cache.time'), function () {
			return $this->model->select('title', 'image')->get();
		});
		return $this->response->withSuccess($list);
	}

	protected function getResourceCollection(Collection $collection): CarouselCollection {
		return new CarouselCollection($collection);
	}

	protected function getResource(CarouselModel $collection): Carousel {
		return new Carousel($collection);
	}
}
